import { User } from "../model/User.js"
import { Op } from "sequelize";

async function queryAllUser(ctx) {

    let users;

    let keyword = ctx.query.keyword;
    console.log(keyword);

    if (keyword) {
        users = await User.findAll({
            where: {
                [Op.or]: {
                    name: {
                        [Op.like]: `%${keyword}%`
                    },
                    age: {
                        [Op.like]: `%${keyword}%`
                    }
                },
            }
        })
    } else {
        users = await User.findAll();
    }

    ctx.body = {
        code: 200,
        msg: "请求列表成功",
        data: users
    }
}

async function queryById(ctx) {
    let id = ctx.params.id

    let user = await User.findByPk(id)

    ctx.body = {
        code: 200,
        msg: "请求单个成功",
        data: user
    }
}

async function delById(ctx) {
    let id = ctx.params.id

    await User.destroy({ where: { id } })

    ctx.body = {
        code: 200,
        msg: "删除单个成功",
        data: null
    }
}

async function add(ctx) {
    let obj = ctx.request.body
    console.log("新增用户", obj);

    await User.create(obj)

    ctx.body = {
        code: 200,
        msg: "新增成功",
        data: null
    }
}

async function update(ctx) {
    let id = ctx.params.id

    let obj = ctx.request.body

    await User.update(obj, { where: { id } })

    ctx.body = {
        code: 200,
        msg: "修改成功",
        data: null
    }
}

export const users = [
    { method: "GET", url: "/users", fn: queryAllUser },
    { method: "GET", url: "/user/:id", fn: queryById },
    { method: "DELETE", url: "/user/:id", fn: delById },
    { method: "POST", url: "/user", fn: add },
    { method: "PUT", url: "/user/:id", fn: update }
]